/*
 * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * This file is part of Harmattan SmashMiner OpenGL game application.
 * 
 * Harmattan SmashMiner OpenGL Example Application version 1.0.0
 *  
 * Latest update: 15.4.2011
 *
 * The Harmattan SmashMiner OpenGL example application demonstrates how to use 
 * the OpenGL ES in Harmattan devices.
 *
 * This example is provided as a starting point for 3rd party
 * developers (you) to ease the implementation of OpenGL based 
 * games. Ideas, parts of code or methodologies that this
 * example application uses can be freely used without restrictions.
 *
 * See file README.txt how to build and compile this example application
 * in the Harmattan SDK environment. 
 * 
 * See file INSTALL.txt to find out what is required to run this
 * application and how to install the application to the device or
 * alternatively in QEMU-emulator.
 *
 * The LICENSE.txt file explains the license this software is provided
 * with. A copy of the same license is included in this source file.
 * 
 */

/*
 * Copyright (C) 2011 by Nokia Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "musicplayer.h"

#include <QDebug>

#ifdef SMASHMINER_CONFIG_ENABLE_MUSIC_PLAYER_GSTREAMER
#include <QApplication>

//
// CALLBACKS
//
/*static void on_pad_added(GstElement *element, GstPad *pad, gpointer data)
{
    Q_UNUSED(element);

    GstPad *sinkpad;
    GstElement *decoder = (GstElement *) data;

    // link this pad with the vorbis-decoder sink pad
    qDebug() << "GStreamer Dynamic pad created, linking demuxer/decoder";

    sinkpad = gst_element_get_static_pad(decoder, "sink");

    gst_pad_link(pad, sinkpad);

    gst_object_unref(sinkpad);
}*/
#endif

/*!
    \class MusicPlayer
    \brief Plays the game music using GStreamer.

    The music file can be OGG or MP3 format.
    OGG format is default. If GStreamer OGG demuxer is not found then the MP3 format is used.
*/

//
// MusicPlayer implementation
//
/*!
 Constructs MusicPlayer.
*/
MusicPlayer::MusicPlayer(int volumeLevel, QObject *parent) : QObject(parent)
  , loopPlayback(false)
  , mp3Playback(false)
  , busTimer(new QTimer(this))
{
#ifdef SMASHMINER_CONFIG_ENABLE_MUSIC_PLAYER_GSTREAMER

#ifdef SMASHMINER_CONFIG_ENABLE_DEBUG_CHECKS
    qDebug() << "MusicPlayer::MusicPlayer() setting_volume_level " << volumeLevel;
#endif  // SMASHMINER_CONFIG_ENABLE_DEBUG_CHECKS

    initGtreamerPipeline();
    setVolumeLevel(volumeLevel);
    connect(busTimer, SIGNAL(timeout()), SLOT(checkBusMessages()));

#else   // SMASHMINER_CONFIG_ENABLE_MUSIC_PLAYER_GSTREAMER

    Q_UNUSED(volumeLevel);

#endif  // SMASHMINER_CONFIG_ENABLE_MUSIC_PLAYER_GSTREAMER
}

/*!
    Destructs MusicPlayer and stops the music playback.
*/
MusicPlayer::~MusicPlayer()
{
    // Stop playback
    stop();

#ifdef SMASHMINER_CONFIG_ENABLE_MUSIC_PLAYER_GSTREAMER

    gst_object_unref(GST_OBJECT(pipeline));

#endif
}

/*!
    Sets the playback volume to the GStreamer pipeline.
*/
void MusicPlayer::setVolumeLevel(int volumeLevel)
{
#ifdef SMASHMINER_CONFIG_ENABLE_DEBUG_CHECKS
    qDebug() << "MusicPlayer::setVolumeLevel() setting_volume_level " << volumeLevel;
#endif  // SMASHMINER_CONFIG_ENABLE_DEBUG_CHECKS

    this->volumeLevel = volumeLevel;

#ifdef SMASHMINER_CONFIG_ENABLE_MUSIC_PLAYER_GSTREAMER

    if (pipeline)
        setPipelineVolume();

#endif  //SMASHMINER_CONFIG_ENABLE_MUSIC_PLAYER_GSTREAMER
}

/*!
    Starts the music playback.
    Plays the sound file once.
*/
void MusicPlayer::play()
{
#ifdef SMASHMINER_CONFIG_ENABLE_MUSIC_PLAYER_GSTREAMER
    if (pipeline && status == PlayerStatusIdle) {
        gst_element_set_state(pipeline, GST_STATE_PLAYING);
        busTimer->start(PeriodTimeMs);
    }
#endif  // SMASHMINER_CONFIG_ENABLE_MUSIC_PLAYER_GSTREAMER
}

/*!
    Starts the music playback.
    Plays the sound file on loop.
*/
void MusicPlayer::playOnLoop()
{
    loopPlayback = true;
    play();
}

/*!
    Stops the music playback.
*/
void MusicPlayer::stop()
{
    loopPlayback = false;

#ifdef SMASHMINER_CONFIG_ENABLE_MUSIC_PLAYER_GSTREAMER

    // out of the main loop, clean up nicely
    status = PlayerStatusIdle;
    gst_element_set_state(pipeline, GST_STATE_NULL);

#endif  // SMASHMINER_CONFIG_ENABLE_MUSIC_PLAYER_GSTREAMER
}

#ifdef SMASHMINER_CONFIG_ENABLE_MUSIC_PLAYER_GSTREAMER

/*!
  Initializes the GStreamer pipeline for music playback.
  If GStreamer OGG demuxer is found uses OGG format else MP3 is used.
*/
void MusicPlayer::initGtreamerPipeline()
{
    // initialisation
    gst_init(NULL, NULL);

    status = PlayerStatusIdle;

    // create gstreamer elements
    pipeline = gst_element_factory_make("playbin2", "file-source");

    if (!pipeline) {
        qWarning() << "GStreamer pipeline elements could not be created";
        status = PlayerStatusError;
        gst_object_unref(GST_OBJECT(pipeline));
        return;
    }

    // set the filepath and location to gstreamer
    if (mp3Playback) {
        filepath = "file:///opt/smashminer/oikophobia.mp3";
    } else {
        filepath = "file:///opt/smashminer/oikophobia.ogg";
    }

    const char *path = filepath.toUtf8();
    g_object_set(G_OBJECT(pipeline), "uri", path, NULL);
}

/*!
  Sets the volume to GStreamer pipeline.
*/
void MusicPlayer::setPipelineVolume()
{
#ifdef SMASHMINER_CONFIG_ENABLE_DEBUG_CHECKS
    qDebug() << "MusicPlayer::setPipelineVolume() setting_volume_level " << volumeLevel;
#endif  // SMASHMINER_CONFIG_ENABLE_DEBUG_CHECKS

    // set volume level to pipeline
    float volLevel = volumeLevel / 10.0f;
    g_object_set(G_OBJECT(pipeline), "volume", volLevel, NULL);
}

/*!
  Checks the pipeline bus messages.
*/
void MusicPlayer::checkBusMessages()
{
    GstBus *bus  = gst_pipeline_get_bus(GST_PIPELINE(pipeline));
    GstMessage *msg;
    while ((msg = gst_bus_pop(bus))) {
        switch (GST_MESSAGE_TYPE(msg)) {

        case GST_MESSAGE_EOS:
            gst_element_set_state(pipeline, GST_STATE_NULL);
            status = PlayerStatusIdle;
            if (loopPlayback)
                play();
            break;

        case GST_MESSAGE_ERROR:
            gchar  *debug;
            GError *error;
            gst_element_set_state(pipeline, GST_STATE_NULL);
            gst_message_parse_error(msg, &error, &debug);
            g_free(debug);
            qWarning() << "GStreamer error: " << error->message;
            g_error_free(error);
            status = PlayerStatusError;
            break;

        default:
            break;
        }
        gst_message_unref(msg);
    }
    gst_object_unref(bus);

    if (status == PlayerStatusPlaying)
        busTimer->start(PeriodTimeMs);
}

#endif

